package com.atguigu.transfrom.split;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class SideOutputDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        DataStreamSource<String> socketDS = env.socketTextStream("10.75.186.206", 9999);

        SingleOutputStreamOperator<WaterSensor> map = socketDS.map(new WaterSensorMapFunction());

        OutputTag<WaterSensor> s1Tag = new OutputTag<WaterSensor>("s1Tag") {};
        OutputTag<WaterSensor> s2Tag = new OutputTag<WaterSensor>("s2Tag") {};

        SingleOutputStreamOperator<WaterSensor> process = map.process(new ProcessFunction<WaterSensor, WaterSensor>() {
            @Override
            public void processElement(WaterSensor value, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                if (value.getId().equals("s1")) {
                    ctx.output(s1Tag, value);
                } else if (value.getId().equals("s2")) {
                    ctx.output(s2Tag, value);
                } else {
                    out.collect(value);
                }
            }
        });

        process.print("主流");
        process.getSideOutput(s1Tag).print("s1");
        process.getSideOutput(s2Tag).print("s2");

        env.execute();
    }
}
